﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarAppDomain.CarType.IRepository;
using CarAppDomain.CarType.Entities;
using D.UtilSqlsugarOrm;
using SqlSugar;
using CarAppDomain.CarParts.Entities;
using System.Linq.Expressions;

namespace CarAppDomain.CarType.Repository
{
    public class CarTypeEntityRepository: BaseRepository<CarTypeEntity>, ICarTypeEntityRepository
    {
        private readonly ISqlSugarClient sqlSugarClient;
        public CarTypeEntityRepository(ISqlSugarClient db) : base(db)
        {
            sqlSugarClient = db;
        }

        public async Task<int> AddCarTypeAsync(CarTypeEntity t, List<CarPartsCarTypeEntity> carPartsCarPartsList)
        {
            //禁止使用 db.Ado.BeginTran,多租户是db.BeginTran
            try
            {
                sqlSugarClient.Ado.BeginTran();
                CarTypeEntity model = sqlSugarClient.Insertable(t).ExecuteReturnEntity();
                if (model == null)
                {
                    sqlSugarClient.Ado.RollbackTran();//插入失败，数据回滚
                    return -1;
                }
                carPartsCarPartsList.ForEach(a=>a.CarTypeId=model.Id);
                await sqlSugarClient.Insertable(carPartsCarPartsList).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception e)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }

        public async Task<int> DeleteCarTypeAsync(List<string> ids)
        {
            try
            {
                sqlSugarClient.Ado.BeginTran();
                await sqlSugarClient.Deleteable<CarTypeEntity>().Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();
                await sqlSugarClient.Deleteable<CarPartsCarTypeEntity>().Where(it => ids.Contains(it.CarTypeId)).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }   

        public async Task<int> UpdateCarTypeAsync(CarTypeEntity t, List<CarPartsCarTypeEntity> carPartsCarPartsList)
        {
            //禁止使用 db.Ado.BeginTran,多租户是db.BeginTran
            try
            {
                sqlSugarClient.Ado.BeginTran();
                sqlSugarClient.Deleteable<CarPartsCarTypeEntity>().Where(a => a.CarTypeId == t.Id).ExecuteCommandAsync();
                await sqlSugarClient.Updateable(t).ExecuteCommandAsync();
                await sqlSugarClient.Insertable(carPartsCarPartsList).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception e)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }
    }
}
